<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="login-background">
      <div class="bg-shape bg-shape-1"></div>
      <div class="bg-shape bg-shape-2"></div>
      <div class="bg-shape bg-shape-3"></div>
    </div>

    <!-- 登录卡片 -->
    <a-card class="login-card" :bordered="false">
      <!-- Logo和标题 -->
      <div class="login-header">
        <div class="login-logo">
          <video-camera-outlined class="logo-icon" />
        </div>
        <h1 class="login-title">IP Camera</h1>
        <p class="login-subtitle">智能网络摄像头管理系统</p>
      </div>

      <!-- 登录表单 -->
      <a-form
        :model="formState"
        name="login"
        class="login-form"
        @finish="handleFinish"
        @finishFailed="handleFinishFailed"
      >
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input
            v-model:value="formState.username"
            size="large"
            placeholder="用户名"
            :disabled="loading"
          >
            <template #prefix>
              <user-outlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password
            v-model:value="formState.password"
            size="large"
            placeholder="密码"
            :disabled="loading"
          >
            <template #prefix>
              <lock-outlined class="input-icon" />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <div class="login-options">
            <a-checkbox v-model:checked="formState.remember_me" :disabled="loading">
              记住登录状态
            </a-checkbox>
          </div>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            block
            class="login-button"
          >
            <template v-if="!loading">
              <login-outlined class="button-icon" />
              <span>登录</span>
            </template>
            <span v-else>登录中...</span>
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 页脚信息 -->
      <div class="login-footer">
        <p class="footer-text">
          <safety-outlined />
          使用安全认证连接
        </p>
      </div>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue';
import {
  UserOutlined,
  LockOutlined,
  VideoCameraOutlined,
  LoginOutlined,
  SafetyOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import SparkMD5 from 'spark-md5';
import SHA256 from 'crypto-js/sha256';
import { getChallenge, login } from '@/api/auth';
import { useRouter } from 'vue-router';

// 获取设备信息
function getDeviceInfo() {
  const userAgent = navigator.userAgent;
  return {
    type: 'browser',
    os: userAgent.includes('Windows') ? 'Windows' :
      userAgent.includes('Mac') ? 'MacOS' :
        userAgent.includes('Linux') ? 'Linux' : 'Unknown',
    client: `${navigator.userAgent.match(/Chrome\/([0-9.]+)/)?.[0] || 'Unknown Browser'}`
  };
}

// 生成设备ID
function generateDeviceId() {
  const storedDeviceId = localStorage.getItem('deviceId');
  if (storedDeviceId) return storedDeviceId;

  // 使用时间戳、随机数和用户代理生成唯一设备ID
  const seed = Date.now() + Math.random() + navigator.userAgent;
  const hash = SparkMD5.hash(seed);
  const newDeviceId = 'device-' + hash.substr(0, 16);
  localStorage.setItem('deviceId', newDeviceId);
  return newDeviceId;
}

// 生成凭证
function generateCredential(password, challenge) {
  return SHA256(password + challenge).toString();
}

export default defineComponent({
  name: 'Login',
  components: {
    UserOutlined,
    LockOutlined,
    VideoCameraOutlined,
    LoginOutlined,
    SafetyOutlined
  },
  setup() {
    const loading = ref(false);
    const router = useRouter();
    const formState = reactive({
      username: '',
      password: '',
      remember_me: true
    });

    const handleFinish = async (values) => {
      try {
        loading.value = true;
        const deviceId = generateDeviceId();

        // 1. 获取挑战码
        const challenge = await getChallenge(values.username, deviceId);

        // 2. 生成凭证
        const credential = generateCredential(values.password, challenge);

        // 3. 执行登录
        const loginData = {
          username: values.username,
          challenge: challenge,
          credential: credential,
          deviceId: deviceId,
          deviceInfo: getDeviceInfo(),
          remember_me: formState.remember_me
        };
        const result = await login(loginData);

        // 存储认证信息
        localStorage.setItem('access_token', result.access_token);
        localStorage.setItem('refresh_token', result.refresh_token);
        localStorage.setItem('token_expires', Date.now() + (result.expires_in * 1000));
        localStorage.setItem('user_info', JSON.stringify(result.user));
        localStorage.setItem('device_id', deviceId);

        message.success('登录成功');
        router.push('/config');

      } catch (error) {
        message.error(error.message || '登录失败,请检查用户名和密码');
      } finally {
        loading.value = false;
      }
    };

    const handleFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
      message.error('请填写所有必填字段');
    };

    return {
      formState,
      loading,
      handleFinish,
      handleFinishFailed,
    };
  },
});
</script>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

/* ==================== 背景装饰 ==================== */
.login-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  z-index: 0;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 20s infinite;
}

.bg-shape-1 {
  width: 300px;
  height: 300px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.bg-shape-2 {
  width: 200px;
  height: 200px;
  top: 60%;
  right: 15%;
  animation-delay: 5s;
}

.bg-shape-3 {
  width: 250px;
  height: 250px;
  bottom: 10%;
  left: 50%;
  animation-delay: 10s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  33% {
    transform: translateY(-30px) rotate(120deg);
  }
  66% {
    transform: translateY(30px) rotate(240deg);
  }
}

/* ==================== 登录卡片 ==================== */
.login-card {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 420px;
  margin: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.ant-card-body) {
  padding: var(--spacing-xl);
}

/* ==================== 登录头部 ==================== */
.login-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.login-logo {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  margin-bottom: var(--spacing-md);
  border-radius: 50%;
  background: linear-gradient(135deg, var(--color-primary) 0%, #40a9ff 100%);
  box-shadow: 0 8px 16px rgba(24, 144, 255, 0.3);
}

.logo-icon {
  font-size: 40px;
  color: #fff;
}

.login-title {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 28px;
  font-weight: 700;
  color: var(--color-text);
  letter-spacing: 1px;
}

.login-subtitle {
  margin: 0;
  font-size: var(--font-size-base);
  color: var(--color-text-secondary);
  font-weight: 400;
}

/* ==================== 登录表单 ==================== */
.login-form {
  margin-top: var(--spacing-lg);
}

:deep(.ant-form-item) {
  margin-bottom: var(--spacing-lg);
}

:deep(.ant-input-affix-wrapper),
:deep(.ant-input-password) {
  border-radius: var(--border-radius-base);
  transition: all var(--transition-base);
}

:deep(.ant-input-affix-wrapper:focus),
:deep(.ant-input-affix-wrapper-focused),
:deep(.ant-input-password:focus),
:deep(.ant-input-password-focused) {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.input-icon {
  color: var(--color-text-tertiary);
  font-size: 16px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.ant-checkbox-wrapper) {
  color: var(--color-text-secondary);
}

/* ==================== 登录按钮 ==================== */
.login-button {
  height: 44px;
  font-size: var(--font-size-lg);
  font-weight: 500;
  border-radius: var(--border-radius-base);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all var(--transition-base);
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.button-icon {
  margin-right: var(--spacing-xs);
}

/* ==================== 登录页脚 ==================== */
.login-footer {
  margin-top: var(--spacing-lg);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--color-border-secondary);
  text-align: center;
}

.footer-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
  margin: 0;
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.footer-text .anticon {
  color: var(--color-success);
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 768px) {
  .login-card {
    margin: var(--spacing-md);
    max-width: 100%;
  }

  :deep(.ant-card-body) {
    padding: var(--spacing-lg);
  }

  .login-logo {
    width: 64px;
    height: 64px;
  }

  .logo-icon {
    font-size: 32px;
  }

  .login-title {
    font-size: 24px;
  }

  .bg-shape {
    display: none;
  }
}

/* ==================== 辅助功能 ==================== */
@media (prefers-reduced-motion: reduce) {
  .bg-shape,
  .login-card {
    animation: none;
  }

  .login-button:hover {
    transform: none;
  }
}
</style>